'use client';

import { useEffect, useState } from 'react';

export default function TestAuthPage() {
  const [authInfo, setAuthInfo] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkAuth();
  }, []);

  async function checkAuth() {
    try {
      // 检查Cookie
      const cookies = document.cookie;
      console.log('Cookies:', cookies);

      // 检查localStorage
      const userStr = localStorage.getItem('user');
      console.log('LocalStorage user:', userStr);

      // 调用API检查认证
      const response = await fetch('/api/auth/me', {
        credentials: 'include',
      });

      const data = await response.json();
      console.log('API Response:', data);

      setAuthInfo({
        cookies,
        localStorage: userStr,
        apiResponse: data,
      });
    } catch (error) {
      console.error('Error:', error);
      setAuthInfo({
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    } finally {
      setLoading(false);
    }
  }

  async function testLogin() {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          username: 'admin',
          password: 'Aoshu.2025',
        }),
      });

      const data = await response.json();
      console.log('Login Response:', data);
      
      // 检查响应头中的Set-Cookie
      console.log('Response Headers:', response.headers);
      
      alert(JSON.stringify(data, null, 2));
      
      // 重新检查认证状态
      checkAuth();
    } catch (error) {
      console.error('Login Error:', error);
      alert('登录失败: ' + (error instanceof Error ? error.message : 'Unknown error'));
    }
  }

  if (loading) {
    return <div className="p-8">加载中...</div>;
  }

  return (
    <div className="p-8 max-w-4xl mx-auto">
      <h1 className="text-2xl font-bold mb-4">认证测试页面</h1>
      
      <button
        onClick={testLogin}
        className="mb-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
      >
        测试登录（admin）
      </button>

      <button
        onClick={checkAuth}
        className="mb-4 ml-2 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
      >
        刷新状态
      </button>

      <div className="bg-gray-100 p-4 rounded">
        <h2 className="font-bold mb-2">认证信息：</h2>
        <pre className="whitespace-pre-wrap text-sm">
          {JSON.stringify(authInfo, null, 2)}
        </pre>
      </div>
    </div>
  );
}
